package com.ruoyi.exen.common.utils.email;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;

/**
 * @author: 许建国
 * @create: 2023-9-1 10:49:48
 * @description:
 */
@Component
public class SendToMail{

    //发件人
    private static String fromEmail;


    @Value("${spring.mail.username}")
    public void setFromEmail(String username) {
        SendToMail.fromEmail = username;
    }



    /**
     * 向用户邮箱发送短信
     *
     * */
    public static void sendEmailMessage(JavaMailSender javaMailSender, String email,String vendor,String msg) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //邮箱发送内容组成
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject("埃克森供应商质量管理系统");
            helper.setText(buildContent(vendor,msg), true);
            helper.setTo(email);
            helper.setFrom(fromEmail);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }



    /**
     * 读取邮件模板
     * 替换模板中的信息
     *
     * @return
     */
    public static String buildContent(String vendor, String msg) {
        //加载邮件html模板
        Resource resource = new ClassPathResource("mailtemplate.ftl");
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //log.info("发送邮件读取模板失败{}", e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(),vendor,msg);
    }


}
